// var wxParse = require('../../wxParse/wxParse.js');
var TOKEN = wx.getStorageSync('token');
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: null,
    img1: '',
    TabCur: 1,
    scrollLeft: 0,
    goods_info: [],
    shop_car_list: [],
    question_list: [],
    commnets_list: [],
    checked_arr_str: "",
    shop_car_num: 0,
    goodDescription: "", //商品详情
    goods_image: '',
    good_price: '',
    path: '../../img/sc.png',
    // 分享
    token: '',
    is_collection: '',
    imagePath: "",
    maskHidden: false,
    canvasHidden: false,
    local_code_url: "",
    bgi: '../../static/personal/bpic_588ku.jpg',
  },


  go_qa_list() {
    let sale_id = this.data.goods_info.id
    wx.navigateTo({
      url: '/pages/goods_qa/goods_qa?sale_id=' + sale_id,
    })
  },


  go_pj_list() {
    let sale_id = this.data.goods_info.id
    wx.navigateTo({
      url: '/pages/goods_comment/goods_comment?sale_id=' + sale_id,
    })
  },





  go_act(e) {
    // console.log(e.currentTarget.dataset.id);
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/activity_info/activity_info?id=' + id,
    })
  },






  checkboxChange(e) {
    let arr = e.detail.value
    this.setData({
      checked_arr_str: arr.toString()
    })
    console.log(this.data.checked_arr_str);
  },


  //预览图片，放大预览
  preview(event) {
    console.log(event.currentTarget.dataset.src, '1111111111')
    let currentUrl = event.currentTarget.dataset.src
    let list = event.currentTarget.dataset.list
    wx.previewImage({
      current: currentUrl, // 当前显示图片的http链接
      urls: list // 需要预览的图片http链接列表
    })
  },
  // 获取商品详情
  get_goods_info(id) {
    var that = this
    app.request("/getSaleDetail", {
      method: "GET",
      data: {
        sale_id: id,
        user_id: wx.getStorageSync('user_id')
      }
    }).then(res => {
      console.log(res, '99999999999999999999999')
      if (res.data.code == 200) {
        var commnets_list = res.data.commnets_list
        var question_list = res.data.question_list
        var goods_info = res.data.res
        goods_info.img_one = goods_info.img_one.split(',')
        goods_info.img_two = goods_info.img_two.split(',')
        res.data.res.goods_desc.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, function (match, capture) {         
          if(capture.indexOf("https")>=0 || capture.indexOf("http")>=0 ){
            var desc  =  res.data.res.goods_desc;
            console.log('包含此字符串')
          }else{
            console.log('不包含此字符串')
           var desc =  res.data.res.goods_desc.replace(/src="/gi, 'src="https://vip.join.ink')
          }
          that.setData({
            goods_desc:desc
          })
        });
        that.setData({
          commnets_list: commnets_list,
          question_list,
          goods_info,
          // goods_desc:res.data.res.goods_desc,
        //  goods_desc:res.data.res.goods_desc.replace(/src="/gi, 'src="https://vip.join.ink'),
          goods_image: res.data.res.cover,
          good_price: res.data.res.price,
          is_collection: res.data.res.is_collection,
          // goodDescription: res.data.res.goods_desc
        })

    

        if (that.data.is_collection == 2) {
          that.setData({
            path: '../../img/sc.png',
          })
        } else {
          is_collection: res.data.res.is_collection
        }

        if (that.data.is_collection == 2) {
          that.setData({
            path: '../../img/sc.png',
          })
        } else {
          that.setData({
            path: '../../img/sc-a.png',
          })
        }

        //   wxParse.wxParse("goodDescription", "html", res.data.res.goods_desc, that, 5);

        //缓存商品图片
        let image = "https://vip.join.ink/" + that.data.goods_image;
        wx.downloadFile({
          url: image,
          success: function (res1) {
            console.log(res1.tempFilePath)
            //缓存商品图片
            that.setData({
              img1: res1.tempFilePath,
              token: wx.getStorageSync('token')
            })
          }
        })


      } else {
        console.log(res.data.msg);
      }
    })
  },


  //购物车下单
  checkout_goods() {
    console.log("get message");

    wx.requestSubscribeMessage({
      tmplIds: [
        'C7cP0N2oKXUyPHHkJeyVi2ngK4AbOuY7d4RFkl3oxvI',
        'MYd9EctnYWK1rWXfnemRDRDeQ9-vrSz0-9IiH83YOxg',
        'uuMwlK2HyQqqkQN9uEgI7ksKkWRlxXgdk5abvT2GboY'
      ],
      success: (res => {
        let ids = this.data.checked_arr_str
        app.request("/user/order/add_order", {
          method: "POST",
          data: {
            id: ids,
            order_type: 1
          }
        }).then(res => {
          console.log(res, "购物车下单");
          let order_no = res.data.orderInfo.order_id
          let pay = res.data.orderInfo.pay
          let url = "/pages/order_list_checkout/order_list_checkout?order_no=" + order_no + "&pay=" + pay
          wx.redirectTo({
            url
          })
          // 支付
          // this.wxpay(order_no)
        }).catch(err => {
          console.log(err, "错误");
        })

      })
    })

  },



  // 详情页下单
  create_order() {
    wx.requestSubscribeMessage({
      tmplIds: [
        'C7cP0N2oKXUyPHHkJeyVi2ngK4AbOuY7d4RFkl3oxvI',
        'C7cP0N2oKXUyPHHkJeyVi2ngK4AbOuY7d4RFkl3oxvI',
        'uuMwlK2HyQqqkQN9uEgI7ksKkWRlxXgdk5abvT2GboY'
      ],
      success: (res => {
        console.log("get message");
        let {
          price,
          id,
          store_id
        } = this.data.goods_info

        console.log(id);
        app.request("/user/gotoOrder", {
          method: "POST",
          data: {
            order_type: 1,
            id,
            store_id,
            price: price * 100
          }
        }).then(res => {
          console.log(res, "详情下单");
          let order_no = res.data.orderList.order_no
          let pay = res.data.orderList.total_price
          let url = "/pages/order_list_checkout/order_list_checkout?order_no=" + order_no + "&pay=" + pay
          wx.redirectTo({
            url
          })
          // 支付
          // this.wxpay(order_no)
        }).catch(err => {
          console.log(err, "错误");
        })

      })

    })
  },


  //加入购物车
  add_goods() {
    let goods_id = this.data.id
    let store_id = this.data.goods_info.store_id
    if (!TOKEN) {

    }
    app.request("/user/add_cart", {
      method: "POST",
      data: {
        pid: goods_id,
        store_id
      }
    }).then(res => {
      console.log(res, "加入购物车");
      if (res.data.code == 200) {
        this.get_shop_car_list()
      }
    })
  },


  delete_goods(e) {
    let id = e.currentTarget.dataset.id
    app.request("/user/cart_del", {
      method: "POST",
      data: {
        id
      }
    }).then(res => {
      console.log(res);
      if (res.data.code == 200) {
        console.log(res.data.msg);
        this.get_shop_car_list()
      }
    })
  },


  goods_num_add(e) {
    console.log(e.detail.currentTarget.dataset.id);
    app.request("/user/cart_reduce", {
      method: "POST",
      data: {
        state: 1,
        id: e.detail.currentTarget.dataset.id
      }
    })
  },

  goods_num_dec(e) {
    console.log(e.detail.currentTarget.dataset.id);
    app.request("/user/cart_reduce", {
      method: "POST",
      data: {
        state: 2,
        id: e.detail.currentTarget.dataset.id
      }
    })
  },

  get_shop_car_list() {
    app.request("/user/cart_list", {}).then(res => {
      console.log(res, "购物车");
      if (res.data.code == 200) {
        this.setData({
          shop_car_list: res.data.data,
          shop_car_num: res.data.data.length
        })
      }
      console.log(this.data.shop_car_list);
    })
  },

  showModal(e) {
    this.get_shop_car_list()
    this.setData({
      modalName: e.currentTarget.dataset.target
    })



  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },

  tabSelect(e) {
    console.log(e);
    this.setData({
      TabCur: e.currentTarget.dataset.id,
      scrollLeft: (e.currentTarget.dataset.id - 1) * 60
    })
  },

  //*************************************** */ 分享商品

  get_code_img(goods_id) {
    let that = this
    let TOKEN = wx.getStorageSync('token')
    console.log(TOKEN, '00000000000000000000000')
    app.request("/user/get_sale_code", {
      data: {
        goods_id
      }
    }).then(res => {
      let code_url = "https://vip.join.ink" + res.data.data
      console.log(code_url);
      wx.downloadFile({
        url: code_url,
        success: (res2) => {
          console.log(res2, "本地");
          that.setData({
            local_code_url: res2.tempFilePath,

          })
        },
        fail(err) {
          console.log(err);
        }
      })
    })

  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this
    console.log(res, '88888888888888888888')
    if (res.from === 'button') {
      console.log("来自页面内转发按钮");
      console.log(res.target);
    } else {
      var pages = getCurrentPages() //获取加载的页面
      var currentPage = pages[pages.length - 1] //获取当前页面的对象
      var url = currentPage.route //当前页面url
      console.log(url, '888888888888')
      console.log("来自右上角转发菜单")
      return {
        title: '好友转发',
        path: url,
        success: (res) => {
          console.log("转发成功", res);
          wx.setStorageSync('token', that.token)
        },
        fail: (res) => {
          console.log("转发失败", res);
        }
      }
    }

  },
  //点击收藏
  click_collection() {
    var that = this
    let goods_id = that.data.id
    let store_id = that.data.goods_info.store_id

    let TOKEN = wx.getStorageSync('token');
    if (TOKEN) {

      app.request("/user/addFavorites", {
        method: "POST",
        data: {
          sale_id: goods_id,
          // store_id,
        }
      }).then(res => {
        console.log(res, "收藏商品");
        if (res.data.code == 200) {
          that.setData({
            path: '../../img/sc-a.png',
          })
          wx.showToast({
            title: '收藏成功',
          })
        } else {


          that.setData({
            path: '../../img/sc.png',
          })
          wx.showToast({
            title: '取消收藏成功',
          })
        }
      })
    } else {
      wx.showModal({
        title: '未登录',
        content: '您还没有登陆 是否前往登录',
        showCancel: true,
        cancelText: "取消",
        confirmText: "登录",
        confirmColor: '#dfb461',
        success: function (res) {
          if (res.cancel) {} else {
            //设置全局变量
            var pages = getCurrentPages() //获取加载的页面
            var currentPage = pages[pages.length - 1] //获取当前页面的对象
            console.log(currentPage.route, '77777777777')
            getApp().globalData.is_login_url = currentPage.route
            getApp().globalData.id = that.data.id
            console.log(app.globalData.is_login_url, "=====================")
            wx.switchTab({
              url: '/pages/personal/personal',
            })
          }
        }
      })
    }
  },

  //将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
  createNewImg1: function () {
    var _this = this;
    var context = wx.createCanvasContext("mycanvas");
    context.setFillStyle('#FFF')
    console.log(this.data.windowW, this.data.windowH)
    context.fillRect(0, 0, this.data.windowW, this.data.windowH)
    var path = _this.data.local_code_url;; //详细看onLoad函数注释部分
    var image = _this.data.img1;
    context.drawImage(image, 30, 20, 300, 250); //这里是商品图片
    this.setSuoming(context);
    this.setName(context);
    this.setMoney(context);
    this.setSuoming1(context);
    context.drawImage(path, 205, 430, 150, 150); //这里是二维码图片
    context.draw()

  },

  //将金额绘制到canvas的固定
  setMoney: function (context) {
    var that = this
    var money = that.data.good_price;
    context.setFontSize(24);
    context.setFillStyle("red");
    context.fillText(money, 40, 360);
    context.stroke();
  },
  //将说明绘制到canvas固定
  setSuoming: function (context) {
    var Suoming = "长按识别小程序码访问"
    context.setFontSize(18);
    context.setFillStyle("#484a3d");
    context.fillText(Suoming, 15, 460);
    context.stroke();
  },
  //将说明2绘制到canvas固定
  setSuoming1: function (context) {
    var Suoming = wx.getStorageSync('user_name')
    context.setFontSize(18);
    context.setFillStyle("#484a3d");
    context.fillText(Suoming, 50, 510);
    context.stroke();
  },

  //将标题绘制到canvas的固定
  setName: function (context) {
    var that = this
    var name = that.data.goods_info.title

    context.setFontSize(15);
    context.setFillStyle("#67695b");
    context.fillText(name, 40, 320);
    context.stroke();
  },
  // 生 成 海报
  createNewImg: function () {

    var that = this;
    var context = wx.createCanvasContext('mycanvas');
    context.fillRect(0, 0, 375, 667)
    var code = that.data.local_code_url;
    let bgi = that.data.bgi
    // context.setTextAlign('center');
    // context.font="30px Arial"

    context.drawImage(bgi, 0, 0, 375, 667);
    // context.drawImage(code, 125,200, 120, 130); 
    var image = that.data.img1;
    context.drawImage(image, 30, 20, 300, 250); //这里是商品图片
    // context.drawImage(path, 30, 20, 300, 250);  //这里是商品图片
    this.setSuoming(context);
    this.setName(context);
    this.setMoney(context);
    this.setSuoming1(context);
    context.drawImage(code, 205, 430, 150, 150); //这里是二维码图片

    context.draw()

    setTimeout(function () {

      wx.canvasToTempFilePath({

        canvasId: 'mycanvas',

        success: function (res) {
          var tempFilePath = res.tempFilePath;
          that.setData({
            imagePath: tempFilePath,
            canvasHidden: true,
            token: wx.getStorage('token')
          });

        },

        fail: function (res) {

          console.log(res);

        }

      });

    }, 200);

  },
  //点击保存到相册
  baocun: function () {
    var that = this
    let filePath = that.data.imagePath
    console.log(filePath)

    //图片保存到本地
    wx.saveImageToPhotosAlbum({
      filePath: filePath,
      success: function (data) {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '您的二维码已保存到相册，赶快识别二维码吧',
          showCancel: false,
        })
      },
      fail: function (err) {
        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
          // 这边微信做过调整，必须要在按钮中触发，因此需要在弹框回调中进行调用
          wx.showModal({
            title: '提示',
            content: '需要您授权保存相册',
            showCancel: false,
            success: modalSuccess => {
              wx.openSetting({
                success(settingdata) {
                  console.log("settingdata", settingdata)
                  if (settingdata.authSetting['scope.writePhotosAlbum']) {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限成功,再次点击图片即可保存',
                      showCancel: false,
                    })
                  } else {
                    wx.showModal({
                      title: '提示',
                      content: '获取权限失败，将无法保存到相册哦~',
                      showCancel: false,
                    })
                  }
                },
                fail(failData) {
                  console.log("failData", failData)
                },
                complete(finishData) {
                  console.log("finishData", finishData)
                }
              })
            }
          })
        }
      },
      complete(res) {
        wx.hideLoading()
      }
    })
    // wx.saveImageToPhotosAlbum({
    //   filePath:filePath,

    //   success(res) {

    //     wx.showModal({

    //       content: '图片已保存到相册，赶紧晒一下吧~',

    //       showCancel: false,

    //       confirmText: '好的',

    //       confirmColor: '#333',

    //       success: function (res) {

    //         if (res.confirm) {

    //           console.log('用户点击确定');
    //           /* 该隐藏的隐藏 */
    //           that.setData({
    //             maskHidden: false
    //           })
    //           wx.navigateBack({
    //             delta: -1,
    //           })

    //         } else {
    //           that.setData({
    //             maskHidden: false
    //           })
    //         }

    //       },
    //       fail: function (res) {

    //         console.log(11111)

    //       }

    //     })

    //   }

    // })

  },
  //点击生成
  formSubmit: function (e) {

    var that = this;
    if (!TOKEN) {
      wx.getUserProfile({
        desc: '登录',
        success: (res) => {
          console.log(res);
          that.setData({
            user_info: res.userInfo,
          })
          let nick_name = res.userInfo.nickName
          let head = res.userInfo.avatarUrl
          wx.setStorageSync('user_info', res.userInfo)
          wx.setStorageSync('user_name', res.userInfo.nickName)

          wx.login({
            success: res => {
              wx.request({
                url: 'https://vip.join.ink/api/getweixinOpenid',
                method: "POST",
                data: {
                  code: res.code
                },
                method: "POST",
                success: res => {
                  console.log(res);
                  wx.request({
                    url: 'https://vip.join.ink/api/login',
                    method: "POST",
                    data: {
                      openid: res.data.openid,
                      head,
                      nick_name
                    },
                    success: result => {
                      console.log(result.data.token);
                      if (result.data.token) {
                        that.setData({
                          hasUserInfo: true
                        })
                        wx.showToast({
                          title: '登陆成功',
                          icon: 'none'
                        })

                      } else(
                        wx.showToast({
                          title: '登陆失败请重新登录',
                          icon: 'none'
                        })
                      )
                      wx.setStorage({
                        data: result.data.token,
                        key: 'token',
                        success: (e) => {
                          let c_date_user = new Date()
                          wx.setStorageSync('user_id', result.data.user.id);
                          wx.setStorageSync('openid', res.data.openid)
                          wx.setStorageSync('c_date_user', c_date_user)
                          this.setData({
                            maskHidden: false
                          });
                          wx.showToast({
                            title: '生成中...',
                            icon: 'loading',
                            duration: 1000
                          });
                          setTimeout(function () {
                            wx.hideToast()
                            that.createNewImg();
                            that.setData({
                              maskHidden: true
                            });
                          }, 1000)
                        }
                      })


                    }
                  })
                }
              })
            }
          })
        }
      })
    } else {


      this.setData({

        maskHidden: false

      });

      wx.showToast({

        title: '生成中...',

        icon: 'loading',

        duration: 1000

      });

      setTimeout(function () {

        wx.hideToast()

        that.createNewImg();

        that.setData({

          maskHidden: true

        });

      }, 1000)
    }
  },



























  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    let id = options.id
    let token = TOKEN

    if (!id) {
      if (token) {
        let scene = decodeURIComponent(options.scene)
        this.get_goods_info(scene)
      }
    } else {
      this.setData({
        id
      })
      that.get_goods_info(id)
      that.get_code_img(id)

      wx.showShareMenu({
        menus: ['shareAppMessage', 'shareTimeline'],
        success(res) {
          console.log(res)
        },
        fail(e) {
          console.log(e)
        }
      })

    }
    console.log(id, "详情");




    // 此处获取设备的宽高。canvas绘制的图片以次宽高为准
    wx.getSystemInfo({
      success: function (res) {
        console.log(res)
        that.setData({
          windowW: res.windowWidth,
          windowH: res.screenHeight,

        })
      },
    })



  },
  //校验缓存中的token 和 通过openid拿到的token进行比对
  check_token() {
    var that = this
    var user_info_token = wx.getStorageSync('token');
    //获取缓存中的openid或者是全局当中的openid变量 通过指定openid查询后台的token 
    wx.request({
      url: 'https://vip.join.ink/api/get_token',
      data: {
        openid: wx.getStorageSync('openid'), //获取缓存中的openid openid不会变
        token: user_info_token
      },
      method: "GET",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res.data)
        if (res.data.code == 200) {
          //此时重新设置新的token作为缓存对象
          wx.setStorageSync('token', res.data.api_token)
          wx.setStorageSync('token_is_agreement', res.data.data) //一致情况下为1
        } else {
          //缓存中的token和后台当中的token不一致  需要重新授权登录
          wx.removeStorageSync('token')
          if (user_info_token != '') {
            wx.showModal({
              title: '提示',
              content: 'token失效，请重新登录！',
              showCancel: false
            })
            setTimeout(function () {
              wx.switchTab({
                url: '/pages/personal/personal',
              })
            }, 2000);
          }

        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},


  //将生成好的图片保存到本地  下面这句注释是文档中的原话。
  // tip: 在 draw 回调里调用canvasToTempFilePath方法才能保证图片导出成功。
  // getImg() {
  //   var _this = this;
  //   wx.canvasToTempFilePath({
  //     canvasId: 'mycanvas',
  //     success: function success(res) {
  //       _this.setData({
  //         imagePath: res.tempFilePath,
  //       });
  //     }
  //   });
  // },

  //点击图片进行预览，长按保存分享图片
  previewImg: function (e) {
    var img = this.data.imagePath
    wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: [img] // 需要预览的图片http链接列表
    })
  },

  gotoSubmit: function (e) {
    var _this = this
    this.setData({
      maskHidden: false,
      showhaibao: true
    })
    wx.showToast({
      title: '图片生成中...',
      icon: 'loading',
      duration: 2000
    });
    setTimeout(function () {
      console.log('gotoSubmit...........................')
      wx.hideToast()
      _this.createNewImg();
    }, 2000)

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    // let id =this.data.id
    // this.get_goods_info(id)
    that.check_token()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // }
})